import type { ListQuery } from "../index";
import { useState, useEffect, useMemo } from "react";
import { OrderStatus, myOrderSetDFH, myOrderGetList, MyOrderItem } from "@/api/modules/order";
import { Table, Tooltip, Space, Button, message, Popconfirm } from "antd";
import { LoginOutlined, SearchOutlined, RedoOutlined } from "@ant-design/icons";
import Cimage from "@/components/Cimage";
import dayjs from "dayjs";
import type { SkuListItem, SpecListItem } from "@/views/goods/set_Sku_data";
import { setSku_list, setSpec_list } from "@/views/goods/set_Sku_data";
import "../index.less";
import { showFullScreenLoading, tryHideFullScreenLoading } from "@/config/serviceLoading";
interface props {
	orderStatus: OrderStatus;
}
interface MyOrderTableItem extends MyOrderItem {
	sku_list?: SkuListItem[];
	spec_list?: SpecListItem[];
}

const table = ({ orderStatus }: props) => {
	const [listQuery, setListQuery] = useState<ListQuery>({
		page: 1,
		size: 10,
		total: 0,
		orderStatus
	});
	const [loading, setLoading] = useState<boolean>(false);
	const [tableData, setTableData] = useState<MyOrderTableItem[]>([]); // 表格数据
	// 初始化获取数据
	useEffect(() => {
		getList(listQuery);
	}, []);
	// 获取订单列表
	async function getList(listQueryRef: ListQuery) {
		setLoading(true);
		try {
			const { code, data } = await myOrderGetList({
				page: listQueryRef.page,
				size: listQueryRef.size,
				orderStatus: listQueryRef.orderStatus
			});
			if (code === 0) {
				setListQuery({
					...listQueryRef,
					total: data.total
				});
				const newList = data.list.map((item: MyOrderTableItem) => {
					item.cart_num = item.list[0].cart_num; // 订单列表list数组只有一个
					if (item.none_sku) {
						// 无规格
						item.sku_list = setSku_list(item.goods, item.none_sku ? "none" : "");
						item.spec_list = setSpec_list(item.goods.skuList, item.none_sku ? "none" : "");
					} else {
						// 有规格
						item.goods.list = item.list; // 替换成已选择的组合列表

						item.sku_list = setSku_list(item.goods, item.none_sku ? "none" : "");
						item.spec_list = setSpec_list(item.goods.skuList, item.none_sku ? "none" : "");
					}
					return item;
				});
				console.log("订单列表数据", newList);
				setTableData(newList);
			}
		} finally {
			setLoading(false);
		}
	}
	// 分页器变化回调
	function handleTableChange(pagination: any) {
		const listQueryRef: ListQuery = {
			...listQuery,
			page: pagination.current,
			size: pagination.pageSize,
			total: pagination.total
		};
		setListQuery(listQueryRef);
		getList(listQueryRef);
	}
	// 去发货
	async function setGoodsOrderStatus(params: { id: number; orderStatus: OrderStatus }) {
		showFullScreenLoading();
		try {
			// 设置订单状态
			const { code, msg } = await myOrderSetDFH(params);
			if (code === 0) {
				message.success(msg);
			}
		} finally {
			tryHideFullScreenLoading();
		}
	}
	// 表格列
	const columns: any[] = [
		{
			title: "下单时间",
			dataIndex: "createTime",
			key: "createTime",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "8%",
			render: (createTime: number) => (
				<Tooltip placement="topLeft" title={dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}>
					{dayjs(createTime || new Date()).format("YYYY-MM-DD HH:mm")}
				</Tooltip>
			)
		},
		{
			title: "订单编号",
			dataIndex: "orderId",
			key: "orderId",
			align: "center",
			width: orderStatus === "DFH" ? "15%" : "20%"
		},
		{
			title: "商品封面",
			dataIndex: "iconId",
			key: "iconId",
			align: "center",
			ellipsis: {
				showTitle: false
			},
			width: "8%",
			className: "iconId_tableClass",
			render: (_: any, record: MyOrderTableItem) => <Cimage src={record.goods.iconId[0].url} width={80} height={80}></Cimage>
		},
		{
			title: "商品名称",
			dataIndex: "name",
			key: "name",
			align: "center",
			width: orderStatus === "DFH" ? "15%" : "20%",
			render: (_: any, record: MyOrderTableItem) => <>{record.goods.name}</>
		},
		{
			title: "购买信息",
			dataIndex: "sku_list",
			key: "sku_list",
			align: "center",
			width: "10%",
			render: (_: any, record: MyOrderTableItem) => (
				<>
					{record.sku_list?.map((item: SkuListItem) => {
						return (
							<div key={item._id} className="sku_list">
								<span>{item.sku_name_arr.toString()}</span>
								<span> x{record.cart_num || 0}</span>
							</div>
						);
					})}
				</>
			)
		},
		{
			title: "订单总价",
			dataIndex: "price",
			key: "price",
			align: "center",
			width: "8%",
			render: (_: any, record: MyOrderTableItem) => (
				<span style={{ color: "#ff6600" }}>{skuListItemPrice(record.sku_list, record.cart_num)}</span>
			)
		},
		{
			title: "订单状态",
			dataIndex: "orderStatus",
			key: "orderStatus",
			align: "center",
			width: "8%",
			render: (_: any, record: MyOrderTableItem) => <span>{orderStatusText(record.orderStatus)}</span>
		},
		{
			title: "买家昵称",
			dataIndex: "userName",
			key: "userName",
			align: "center",
			width: "8%",
			render: (_: any, record: MyOrderTableItem) => <>{record.user.userName || "未命名买家"}</>
		},
		{
			title: "操作",
			align: "center",
			key: "action",
			width: orderStatus === "DFH" ? "20%" : "10%",
			render: (_: any, record: MyOrderTableItem) => (
				<Space wrap>
					<Button icon={<SearchOutlined />}>详情</Button>
					{orderStatus === "DFH" && (
						<Popconfirm
							title="确定执行该操作吗？"
							onConfirm={() => setGoodsOrderStatus({ id: record.id, orderStatus: OrderStatus.DSH })}
							okText="Yes"
							cancelText="No"
						>
							<Button icon={<LoginOutlined />} danger>
								发货
							</Button>
						</Popconfirm>
					)}
				</Space>
			)
		}
	];
	return (
		<>
			<Space direction="vertical" align="end" className="flex items-center">
				<Button
					type="primary"
					icon={<RedoOutlined />}
					onClick={() => {
						getList(listQuery);
					}}
				>
					刷新
				</Button>
				<Table
					loading={loading}
					bordered={false}
					dataSource={tableData}
					columns={columns}
					rowKey={record => record.id}
					pagination={{
						current: listQuery.page, // 当前页码
						pageSize: listQuery.size, // 每页条数
						total: listQuery.total, // 数据总数
						showSizeChanger: true, // 显示每页条数切换器
						showQuickJumper: true // 显示快速跳转输入框
					}}
					onChange={pagination => handleTableChange(pagination)} // 分页变化回调
				/>
			</Space>
		</>
	);
};
// 过滤方法
function skuListItemPrice(sku_list: SkuListItem[] | undefined, cart_num: number | undefined) {
	// 计算订单总价
	const prices = sku_list!.map(item => Number(item.price) * cart_num!);
	return prices.length > 0 ? prices.reduce((n, m) => n + m).toFixed(2) : 0;
}
function orderStatusText(status: string) {
	// 订单状态文案转换
	switch (status) {
		case "DFK":
			return "待付款";
		case "DFH":
			return "待发货";
		case "DSH":
			return "待收货";
		case "DPJ":
			return "待评价";
		case "YQX":
			return "已取消";
		case "YWC":
			return "已完成";
	}
}
export default table;
